<template>
  <el-card class="mainContainer" shadow="never">
    <div ref="searchRef">
      <el-form :inline="true" :model="formInline"
               v-show="showSearch"
               class="demo-form-inline animate__animated animate__fadeIn">
        <el-form-item label="权限名称：">
          <el-input v-model="formInline.name" placeholder="权限名称" clearable/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="queryTable">查询</el-button>
          <el-button type="info" @click="setFormInline();queryTable()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row :gutter="10" class="margin-bottom-18"
            style="margin-left: 0;margin-right: 0"
            type="flex" justify="space-between">
      <el-col :span="1.5" style="padding: 0">
        <el-button
            type="primary"
            :icon="Message"
            size=small
            @click="openCreateMenuForm"
        >新建菜单
        </el-button>
      </el-col>

      <el-col :span="1.5" style="padding: 0">
        <RightToolbar :show-search="showSearch"
                      @updateShowSearch="updateShowSearch"
                      @queryTable="queryTable"/>
      </el-col>
    </el-row>


    <el-table :data="tableData" border
              row-key="id"
              :height="max_table_height"
              cell-class-name="custom_table_column"
              style="width: 100%">
      <el-table-column prop="menuType" align="center" label="菜单类型" width="140"/>
      <el-table-column align="center" label="菜单图标" width="100">
        <template #default="scope">
          <unicon :name="scope.row.icon.name" :fill="scope.row.icon.fill" :icon-style="scope.row.icon.iconStyle"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="权限名称">
        <template #default="scope">
          <el-text>{{ scope.row.name }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="sort" align="center" label="菜单排序" width="100"/>
      <el-table-column prop="web_path" align="center" label="路由地址"/>
      <el-table-column prop="perms" align="center" label="权限标识"/>
      <el-table-column prop="create_datetime" align="center" label="创建时间" width="160"/>
      <el-table-column prop="update_datetime" align="center" label="修改时间" width="160"/>
      <el-table-column align="center" label="操作" min-width="150px">
        <template #default="scope">
          <el-button
              @click="openUpdateMenuForm(scope.row.id)"
              size="small">编辑
          </el-button>
          <el-button
              size="small"
              @click="commitDeleteMenu(scope.row.id)"
              type="danger">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


  </el-card>


  <!--  新建/编辑框-->
  <div>
    <el-dialog
        v-model="MenuDialog"
        :title="MenuDialogTitle"
        width="500"
        :before-close="MenuDialogClose"
        :fullscreen="false"
    >

      <el-form :model="MenuFormData" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="规则类型:">
              <el-radio-group :disabled="MenuFormDataShow.isUpdate" v-model="MenuFormData.permType">
                <el-radio label="first" value="" border>菜单目录</el-radio>
                <el-radio label="second" border>菜单项</el-radio>
                <el-radio label="button" border>页面按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="MenuFormDataShow.parentMenu" :span="24">
            <el-form-item label="上级菜单:">
              <el-cascader
                  filterable
                  style="width: 100%;"
                  v-model="MenuFormData.parentMenu"
                  :options="parentMenu"
                  :props="{expandTrigger: 'hover'}"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="图标样式:">
              <el-select style="width: 100%;"
                         v-model="MenuFormData.icon.iconStyle" placeholder="图标样式">
                <el-option label="line " value="line"/>
                <el-option label="monochrome" value="monochrome"/>
                <el-option label="solid" value="solid"/>
                <el-option label="thinline" value="thinline"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标颜色:">
              <el-color-picker v-model="MenuFormData.icon.fill"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限图标:">
              <el-select defaultFirstOption
                         placeholder="权限图标" clearable
                         style="width: 100%;" filterable
                         v-model="MenuFormData.icon.name">
                <template #prefix>
                  <unicon :name="MenuFormData.icon.name" :fill="MenuFormData.icon.fill"
                          :icon-style="MenuFormData.icon.iconStyle"/>
                </template>

                <template #default>
                  <el-option v-for="item in IconsNameS" :value="item">
                      <span class="iconItem" style="float: left">
                        <unicon :name="item" :fill="MenuFormData.icon.fill" :icon-style="MenuFormData.icon.iconStyle"/>
                      </span>
                    <span style="float: right">{{ item }}</span>
                  </el-option>
                </template>

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限名称:">
              <el-input v-model.trim="MenuFormData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="MenuFormDataShow.web_path">
            <el-form-item label="路由地址:">
              <el-input v-model.trim="MenuFormData.web_path"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限标识:">
              <el-input v-model.trim="MenuFormData.perms"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限排序:">
              <el-input-number style="width: 100%;" v-model.number="MenuFormData.sort">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限备注:">
              <el-input type="textarea" v-model.trim="MenuFormData.description"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否开启:">
              <el-radio-group v-model="MenuFormData.status">
                <el-radio :label="true" border>开启</el-radio>
                <el-radio :label="false" border>禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>


      <template #footer>
      <span class="dialog-footer">
        <el-button @click="MenuDialogClose">取消</el-button>
        <el-button type="primary" @click="commitMenuFormData">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>

</template>


<script setup>
//userIndex 用户
import RightToolbar from '@/components/RightToolbar/index.vue'
import {ref, reactive, onMounted, onUnmounted, nextTick, watch} from 'vue'
import {
  Message,
  Delete
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getMenuList, getMenu, getParentMenu, postMenu, deleteMenu, putMenu} from "@/apis/system/menu.js";
import {deepCopy} from '@/util/tools.js'


const searchRef = ref(null)
const max_table_height = ref("calc(100vh - 305px)")

const update_max_table_height = () => {
  max_table_height.value = "calc(100vh - 205px - " + searchRef.value.clientHeight + "px)"
}

onMounted(() => {
  nextTick(update_max_table_height);
  addEventListener("resize", update_max_table_height);
})
onUnmounted(() => {
  removeEventListener("resize", update_max_table_height);

})

const showSearch = ref(true)
const updateShowSearch = () => {
  showSearch.value = !showSearch.value;
  nextTick(update_max_table_height);
}

let tableData = ref([])

const formInlineSource = {
  name: '',
}

const formInline = reactive({})

const setFormInline = () => {
  Object.assign(formInline, deepCopy(formInlineSource))
}

onMounted(() => {
  setFormInline()
})


const queryTable = async () => {
  getMenuList(qs.stringify(formInline)).then(res => {
    tableData.value = res.data;
  })
}

onMounted(() => {
  queryTable();
})


// ########   表单页  ##################
const MenuDialog = ref(false)
const MenuDialogTitle = ref('')
import IconsNameS from '@/util/UnIcons.js'

const parentMenu = ref([])

const MenuFormDataSource = {
  permType: 'first',
  parentMenu: null,
  icon: {name: 'home', fill: '#00C8FF', iconStyle: 'line'},
  name: '',
  web_path: '',
  perms: '',
  sort: 0,
  status: true,
  description: ''
}

let MenuFormData = reactive({})

const openCreateMenuForm = () => {
  Object.assign(MenuFormData, deepCopy(MenuFormDataSource))
  MenuDialog.value = true;
  MenuFormDataShow.isUpdate = false;
  MenuDialogTitle.value = '新建菜单';
}
const openUpdateMenuForm = async (id) => {
  getMenu(id).then(res => {
    Object.assign(MenuFormData, deepCopy(res.data));
    MenuDialog.value = true;
    MenuFormDataShow.isUpdate = true;
    MenuFormDataShow.updateId = id;
    MenuDialogTitle.value = '编辑菜单';
  })
}


const MenuFormDataShow = reactive({
  isUpdate: true,
  updateId: '',
  parentMenu: true,
  web_path: true,
})

/** 监听菜单选择 **/
watch(() => MenuFormData.permType, async (value, oldValue) => {
  if (oldValue && value !== oldValue) {
    MenuFormData.parentMenu = null
  }

  if (value === 'first') {
    MenuFormDataShow.parentMenu = false;
    MenuFormDataShow.web_path = true;
  }
  if (value === 'second') {
    MenuFormDataShow.parentMenu = true;
    MenuFormDataShow.web_path = true;
    getParentMenu(qs.stringify({"permType": "second"})).then(res => {
      parentMenu.value = res.data
    });
  }
  if (value === 'button') {
    MenuFormDataShow.parentMenu = true;
    MenuFormDataShow.web_path = false;
    getParentMenu(qs.stringify({"permType": "button"})).then(res => {
      parentMenu.value = res.data
    });
  }

}, {immediate: true, deep: true})


const MenuDialogClose = () => {
  ElMessageBox.confirm('取消操作？')
      .then(() => {
        MenuDialog.value = false;
        done()
      })
      .catch(() => {
        // catch error
      })
}

const commitMenuFormData = async () => {
  if (!MenuFormDataShow.isUpdate) {
    postMenu(MenuFormData).then(res => {
      // console.log(res)
      MenuDialog.value = false;
      queryTable();
      ElMessage({
        message: res.data,
        type: 'success',
      });
    })
  } else {
    putMenu(MenuFormDataShow.updateId, MenuFormData).then(res => {
      // console.log(res)
      MenuDialog.value = false;
      queryTable();
      ElMessage({
        message: res.data,
        type: 'success',
      });
    })
  }
}

const commitDeleteMenu = async (id) => {
  ElMessageBox.confirm('确定要删除？该删除会直接在数据库删除！！')
    .then(() => {
      deleteMenu(id).then(res => {
        queryTable();
        ElMessage({
          message: res.data,
          type: 'success',
        });
      })
      done()
    })
    .catch(() => {
      // catch error
    })
    }
</script>

<style lang="scss">
.unicon {
  padding-top: 10px;
}

.iconItem {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;

  .unicon {
    padding-top: 5px;
  }
}

</style>
